/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.server.dao.impl;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.niiuzu.server.dao.ParameterDao;
import com.niiuzu.server.dao.exception.DaoException;
import com.niiuzu.server.dao.impl.dto.object.DtoParameter;
import com.niiuzu.server.model.ParameterName;

/**
 * Implémentation du DAO dédié aux paramètres de l'application.
 */
public class ParameterDaoImpl extends AbstractDatastoreDao implements
		ParameterDao {

	private static final Logger LOGGER = Logger
			.getLogger(ParameterDaoImpl.class.getName());

	static {
		ObjectifyService.register(DtoParameter.class);
	}

	@Override
	public String getParameterValue(ParameterName name) throws DaoException {

		LOGGER.info("Début de récupération du paramètre " + name);

		String value = null;

		try {

			if (name == null) {
				throw new IllegalArgumentException(
						"Parameter name cannot be null.");
			} else {

				Objectify objectify = createObjectify(false);

				String parameterName = name.name();
				DtoParameter dtoParameter = objectify.get(DtoParameter.class,
						parameterName);

				// Paramètre introuvable
				if (dtoParameter == null) {
					StringBuilder errorMsg = new StringBuilder();
					errorMsg.append("Parameter `");
					errorMsg.append(name);
					errorMsg.append("` doesn't exist in the datastore.");
					throw new IllegalStateException(errorMsg.toString());
				} else {
					value = dtoParameter.getValue();
				}
			}

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE,
					"Erreur lors de la récupération du paramètre " + name, e);
			throw new DaoException(e);
		} finally {
			LOGGER.info("Fin de récupération du paramètre " + name);
		}

		return value;
	}

	@Override
	public boolean isParameterEnabled(ParameterName name) throws DaoException {
		String parameterValue = getParameterValue(name);
		return Boolean.parseBoolean(parameterValue);
	}

}
